// pages/issued-invoice/issued-invoice.js
Page({
  data: {
    currentPatient: {
      name: '',
      relationship: '本人',
      cardNumber: ''
    },
    patientList: [],
    showPatientModal: false,
    timeFilter: '近一年', // '近一年' 或 '选择时间'
    startYear: 2024,
    startMonth: '01',
    startDay: '01',
    endYear: 2024,
    endMonth: '01',
    endDay: '01',
    isSelectingStart: true, // true表示正在选择开始日期，false表示正在选择结束日期
    showTimeModal: false,
    invoiceList: [],
    pickerValue: [0, 0, 0], // picker-view的value，对应2024年01月01日
    yearList: [2024, 2023, 2022, 2021, 2020],
    monthList: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'],
    dayList: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31']
  },

  onLoad: function(options) {
    this.loadPatientInfo();
    this.loadInvoiceData();
    this.initPickerValue();
  },

  // 加载就诊人信息
  loadPatientInfo: function() {
    wx.request({
      url: 'http://localhost:8005/patient/list',
      method: 'GET',
      header: { 'Content-Type': 'application/json' },
      success: (res) => {
        if (res.statusCode === 200 && res.data) {
          let list = res.data
          if (typeof list === 'string') {
            try { list = JSON.parse(list) } catch (e) { return }
          }
          if (list.code !== undefined) list = list.data
          if (!Array.isArray(list)) return
          
          // 保存完整的就诊人列表
          const mapped = list.map(p => ({
            id: p.id,
            name: p.name,
            relationship: p.relationTypeName || '本人',
            cardNumber: (p.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2')
          }))
          
          this.setData({ patientList: mapped })
          
          // 找到默认就诊人
          const defaultPatient = list.find(p => p.isDefault === 1)
          if (defaultPatient) {
            this.setData({
              currentPatient: {
                name: defaultPatient.name,
                relationship: defaultPatient.relationTypeName || '本人',
                cardNumber: (defaultPatient.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2')
              }
            })
          } else {
            // 如果没有默认就诊人，使用第一个就诊人
            const firstPatient = list[0]
            if (firstPatient) {
              this.setData({
                currentPatient: {
                  name: firstPatient.name,
                  relationship: firstPatient.relationTypeName || '本人',
                  cardNumber: (firstPatient.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2')
                }
              })
            }
          }
        }
      }
    })
  },

  // 初始化picker值
  initPickerValue: function() {
    const yearIndex = this.data.yearList.indexOf(this.data.startYear);
    const monthIndex = this.data.monthList.indexOf(this.data.startMonth);
    const dayIndex = this.data.dayList.indexOf(this.data.startDay);
    
    this.setData({
      pickerValue: [yearIndex, monthIndex, dayIndex]
    });
  },

  // 加载发票数据
  loadInvoiceData: function() {
    const { timeFilter, selectedYear } = this.data;
    let invoiceList = [];

    if (timeFilter === '近一年') {
      // 2025年的数据
      invoiceList = [
        {
          id: '001',
          date: '2025-01-15 11:05',
          department: '神经内科',
          amount: '56',
          invoiceNumber: 'INV202501150001',
          payer: '蒋峰'
        },
        {
          id: '002',
          date: '2025-01-10 14:30',
          department: '神经内科',
          amount: '56',
          invoiceNumber: 'INV202501100002',
          payer: '蒋峰'
        },
        {
          id: '003',
          date: '2025-01-08 09:15',
          department: '神经内科',
          amount: '56',
          invoiceNumber: 'INV202501080003',
          payer: '蒋峰'
        },
        {
          id: '004',
          date: '2025-01-05 16:45',
          department: '神经内科',
          amount: '56',
          invoiceNumber: 'INV202501050004',
          payer: '蒋峰'
        }
      ];
    } else {
      // 其他年份的数据
      const yearData = {
        2024: [
          {
            id: '005',
            date: '2024-12-20 10:30',
            department: '神经内科',
            amount: '56',
            invoiceNumber: 'INV202412200005',
            payer: '蒋峰'
          },
          {
            id: '006',
            date: '2024-11-15 13:20',
            department: '神经内科',
            amount: '56',
            invoiceNumber: 'INV202411150006',
            payer: '蒋峰'
          }
        ],
        2023: [
          {
            id: '007',
            date: '2023-08-10 11:00',
            department: '神经内科',
            amount: '56',
            invoiceNumber: 'INV202308100007',
            payer: '蒋峰'
          }
        ],
        2022: [
          {
            id: '008',
            date: '2022-06-15 09:45',
            department: '神经内科',
            amount: '56',
            invoiceNumber: 'INV202206150008',
            payer: '蒋峰'
          }
        ],
        2021: [
          {
            id: '009',
            date: '2021-03-20 14:15',
            department: '神经内科',
            amount: '56',
            invoiceNumber: 'INV202103200009',
            payer: '蒋峰'
          }
        ]
      };
      invoiceList = yearData[selectedYear] || [];
    }

    this.setData({ invoiceList });
  },

  // 显示切换就诊人弹窗
  showPatientSelector: function() {
    this.setData({
      showPatientModal: true
    });
  },

  // 隐藏切换就诊人弹窗
  hidePatientSelector: function() {
    this.setData({
      showPatientModal: false
    });
  },

  // 选择就诊人
  selectPatient: function(e) {
    const patient = e.currentTarget.dataset.patient;
    this.setData({
      currentPatient: patient,
      showPatientModal: false
    });

    // 保存到本地存储
    const cacheUser = wx.getStorageSync('userInfo') || {}
    wx.setStorageSync('userInfo', { ...cacheUser, patientId: patient.id })

    this.loadInvoiceData();
  },

  // 阻止事件冒泡
  stopPropagation: function() {
    // 阻止事件冒泡
  },

  // 切换时间筛选
  switchTimeFilter: function(e) {
    const filter = e.currentTarget.dataset.filter;
    this.setData({
      timeFilter: filter
    });

    if (filter === '近一年') {
      this.setData({
        selectedYear: 2025
      });
      this.loadInvoiceData();
    } else {
      this.showTimeSelector();
    }
  },

  // 显示时间选择弹窗
  showTimeSelector: function() {
    this.setData({
      showTimeModal: true
    });
  },

  // 隐藏时间选择弹窗
  hideTimeSelector: function() {
    this.setData({
      showTimeModal: false
    });
  },

  // picker-view变化事件
  onPickerChange: function(e) {
    const values = e.detail.value;
    const yearIndex = values[0];
    const monthIndex = values[1];
    const dayIndex = values[2];
    
    if (this.data.isSelectingStart) {
      // 选择开始日期
      this.setData({
        startYear: this.data.yearList[yearIndex],
        startMonth: this.data.monthList[monthIndex],
        startDay: this.data.dayList[dayIndex],
        pickerValue: values
      });
    } else {
      // 选择结束日期
      this.setData({
        endYear: this.data.yearList[yearIndex],
        endMonth: this.data.monthList[monthIndex],
        endDay: this.data.dayList[dayIndex],
        pickerValue: values
      });
    }
  },

  // 确认时间选择
  confirmTimeSelection: function() {
    this.setData({
      showTimeModal: false,
      timeFilter: '选择时间',
      selectedYear: this.data.startYear // 使用开始日期作为筛选条件
    });
    this.loadInvoiceData();
  },

  // 取消时间选择
  cancelTimeSelection: function() {
    this.setData({
      showTimeModal: false
    });
  },

  // 点击开始日期输入框
  selectStartDate: function() {
    this.setData({
      isSelectingStart: true
    });
    this.updatePickerValue(true);
  },

  // 点击结束日期输入框
  selectEndDate: function() {
    this.setData({
      isSelectingStart: false
    });
    this.updatePickerValue(false);
  },

  // 更新picker值
  updatePickerValue: function(isStart) {
    let year, month, day;
    if (isStart) {
      year = this.data.startYear;
      month = this.data.startMonth;
      day = this.data.startDay;
    } else {
      year = this.data.endYear;
      month = this.data.endMonth;
      day = this.data.endDay;
    }
    
    const yearIndex = this.data.yearList.indexOf(year);
    const monthIndex = this.data.monthList.indexOf(month);
    const dayIndex = this.data.dayList.indexOf(day);
    
    this.setData({
      pickerValue: [yearIndex, monthIndex, dayIndex]
    });
  },

  // 点击发票项
  selectInvoice: function(e) {
    const invoiceId = e.currentTarget.dataset.id;
    const invoice = this.data.invoiceList.find(item => item.id === invoiceId);
    
    wx.navigateTo({
      url: `/pages/invoice-detail/invoice-detail?invoiceId=${invoice.id}&date=${invoice.date}&department=${invoice.department}&amount=${invoice.amount}&invoiceNumber=${invoice.invoiceNumber}&payer=${invoice.payer}`
    });
  }
});
